<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
         <!-- <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="数据日期">
              <j-date placeholder="请选择数据日期" v-model="queryParam.sjrq"  style="width: 220px" @change="judgeSjrq"></j-date>
            </a-form-item>
          </a-col>-->

          <a-col :xl="10" :lg="7" :md="8" :sm="24">
            <a-form-item label="日期范围" :required="true" >
              <a-range-picker v-model="queryParam.birthdayRange"
                              format="YYYY-MM-DD"
                              :placeholder="['开始时间', '结束时间']"
                              @change="onBirthdayChange"
                              :style="{width: '300px'}"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="主题">
              <j-tree-select
                ref="treeSelect"
                placeholder="请选择主题"
                v-model="queryParam.theme"
                dict="llbb_param_config,name,code"
                pidValue="1506488476828733442"
                hasChildField="has_child"
              >
              </j-tree-select>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="search(1)" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset1" icon="reload" style="margin-left: 8px">重置</a-button>
              <!--<a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>-->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="createRebortData" type="primary" v-has="'report:bathSave'" >批量生成</a-button>
<!--      <a-button @click="dayCheck" type="primary" >批量校验</a-button>-->
<!--      <a-button @click="dayDown" type="primary" v-has="'report:dayDown'">批量下载</a-button>-->
      <a-button @click="daySourceDown" type="primary">批量下载源文件</a-button>
      <a-button @click="dayAfresh" type="primary" v-has="'report:dayAfresh'" >重新报送</a-button>
      <!--<a-button @click="dayRepulse" type="primary"  v-has="'report:dayRepulse'" >打回</a-button>-->
      <!--<a-button @click="dayDelete" type="primary"  v-has="'report:dayRepulse'" >删除</a-button>&nbsp;&nbsp;&nbsp;&nbsp;-->
      <!--<a-button @click="createDown" type="primary">个人存款基础信息发生额变化数据报文下载</a-button>-->
      <a-button @click="handleUpload" type="primary">报文上报</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="reprotDetailList(record)" >{{record.BANKNAME}}</a>
        </span>

      </a-table>
    </div>
     <day-report-item-list ref="dayReportItemList"></day-report-item-list>
    <day-repor-modal ref="modalForm" @ok="modalFormOk"></day-repor-modal>


    <j-modal
      :visible.sync="modal.visible"
      :width="600"
      :title="modal.title"
      :fullscreen.sync="modal.fullscreen"
      :switchFullscreen="modal.switchFullscreen"
    >

      <template v-for="(i,k) in dataList">
        <p :key="k">{{i}}</p>
      </template>
      <template slot="footer">
        <a-button @click="this.closeWindow" type="primary">关闭</a-button>
      </template>
    </j-modal>

    <SjrqModal ref="SjrqModal" :handleAdd="creatDownHandle"></SjrqModal>
  </a-card>
</template>

<script>

  import SjrqModal from '../../common/sjrq/SjrqModal'
  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import DayReporModal from './modules/DayReporModal'
  import DayReportItemList from './DayReportItemList'
  import {downloadFile, httpAction,getAction} from '@/api/manage'
var result= [];
  export default {
    name: 'DayReporList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      DayReporModal,
      DayReportItemList,
      SjrqModal
    },
    data () {
      return {
        modal: {
          title: '未提交业务表',
          visible: false,
          fullscreen: false,
          switchFullscreen: false,
        },
        dataList:[],
        description: '日报报文',
        disableMixinCreated: true,
        // 表头
        columns: [
          {
            title: '选项',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'报送任务日期',
            align:"center",
            dataIndex: 'REPORTTASKDATE'
          },
          {
            title:'数据日期',
            align:"center",
            dataIndex: 'DATADATE'
          },
          {
            title: '法人名称',
            dataIndex: 'action',
            align: "center",
            scopedSlots: {
              customRender: 'action'},
          },
          {
            title:'主题名称',
            align:"center",
            dataIndex: 'THEMENAME'
          },
          {
            title:'总分片数',
            align:"center",
            dataIndex: 'TOTALSEPARATE'
          },
          {
            title:'总记录行',
            align:"center",
            dataIndex: 'TOTALROWNUM'
          },
          {
            title:'生成成功',
            align:"center",
            dataIndex: 'CREATESTATE'
          },
          {
            title:'校验成功',
            align:"center",
            dataIndex: 'VERIFYSTATE'
          },
          {
            title:'上报成功',
            align:"center",
            dataIndex: 'REPORTSTATE'
          },
          {
            title:'重报成功',
            align:"center",
            dataIndex: 'REPORTFLAG'
          },
          {
            title:'反馈成功',
            align:"center",
            dataIndex: 'FEEDBACK'
          },
          {
            title: '操作时间',
            align: "center",
            dataIndex: 'UPDATE_TIME',
          },/*,
          {
            title: '法人名称',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }*/
        ],
        queryParam: {
          sjrq: "",
          bankNoCd: "",
          beginData:"",
          endData:"",
          theme:""
        },
        url: {
          list: "/messagemanagement/llbbMessageManagement/findDayReportPageListNew",
          delete: "/corporateCustomer/llbbCorporateCustomer/delete",
          deleteBatch: "/corporateCustomer/llbbCorporateCustomer/deleteBatch",
          exportXlsUrl: "/corporateCustomer/llbbCorporateCustomer/exportXls",
          importExcelUrl: "corporateCustomer/llbbCorporateCustomer/importExcel",
        },
        dictOptions:{},
        superFieldList:[],
        checkPagam:{
          sjrq:[],
          bankNoCd:[]
        }
      }
    },
    created() {
    this.getSuperFieldList();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      search(arg) {
        if(this.queryParam.beginData == '' || this.queryParam.beginData == undefined){
          this.$message.error("请输入开始时间!")
          return
        }
        if(this.queryParam.endData == '' || this.queryParam.endData == undefined){
          this.$message.error("请输入结束时间!")
          return
        }
        if(!this.url.list){
          this.$message.error("请设置url.list属性!")
          return
        }
        this.selectedRowKeys=[];
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        var params = this.getQueryParams();//查询条件
        this.loading = true;
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records||res.result;
            if(res.result.total)
            {
              this.ipagination.total = res.result.total;
            }else{
              this.ipagination.total = 0;
            }
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          }
          /* if(res.code===500){
             this.$message.warning(res.message)
           }*/
          if(res.code===510){
            this.$message.warning(res.message)
          }
          this.loading = false;
        })
      },
      onBirthdayChange: function (value, dateString) {
        result.length = 0
        console.log(dateString[0],dateString[1]);
        this.queryParam.beginData=dateString[0];
        this.queryParam.endData=dateString[1];
        if(this.queryParam.beginData == this.queryParam.endData && this.queryParam.beginData != '' && this.queryParam.endData != ''){
          result.push(this.queryParam.beginData);
        }else if(this.queryParam.beginData != '' && this.queryParam.endData != ''){
          this.getBetweenDateStr( this.queryParam.beginData,this.queryParam.endData)
        }
      },
      getBetweenDateStr(start,end){
      var beginDay = start.split("-");
      var endDay = end.split("-");
      var diffDay = new Date();
      var dateList = new Array;
      var i = 0;
      diffDay.setDate(beginDay[2]);
      diffDay.setMonth(beginDay[1]-1);
      diffDay.setFullYear(beginDay[0]);
      result.push(start);
      while(i == 0){
        var countDay = diffDay.getTime() + 24 * 60 * 60 * 1000;
        diffDay.setTime(countDay);
        dateList[2] = diffDay.getDate();
        dateList[1] = diffDay.getMonth() + 1;
        dateList[0] = diffDay.getFullYear();
        if(String(dateList[1]).length == 1){dateList[1] = "0"+dateList[1]};
        if(String(dateList[2]).length == 1){dateList[2] = "0"+dateList[2]};
        result.push(dateList[0]+"-"+dateList[1]+"-"+dateList[2]);
        if(dateList[0] == endDay[0] && dateList[1] == endDay[1] && dateList[2] == endDay[2]){ i = 1;
        }
      };
      },
      closeWindow(){
        this.$emit('close');
        this.modal.visible = false;
      },
      createDown(){console.log(this.$refs)
        this.$refs.SjrqModal.showModal('createDown');
      },
      creatDownHandle(value){
        let url=`${window._CONFIG['domianURL']}`+"/messagemanagement/llbbMessageManagement/dayReportDown?sjrq="+value +
          "&bankNoCd=C1081621000014&tableCode=GRCKJC";
        /* window.open(url);*/
        try {
          var elemIF = document.createElement("iframe");
          elemIF.src = url;
          elemIF.style.display = "none";
          document.body.appendChild(elemIF);
        } catch (e) {
          console.log(e)
        }
      },
      judgeSjrq(){
        var oDate1 = new Date(this.queryParam.sjrq);
        var oDate2 = new Date();
        if(oDate1.getTime() > oDate2.getTime()){
          this.queryParam.sjrq='';
          this.$message.warning("数据日期不能大于当前日期，请重新选择");
        }
      },
      dayDown(){
        const that = this;
        if(this.selectedRowKeys.length==0){
          that.$message.warning("请选择你要批量下载的数据");
          return false;
        }
        var bool=false;
        for(var i=0;i<this.selectedRowKeys.length;i++) {
          if(this.dataSource[this.selectedRowKeys[i]].CREATESTATE==0){
            bool=true;
            break;
          }
        }
        // if(bool){
        //   that.$message.warning("只能选择生成成功数大于0的数据");
        //   return;
        // }
        for (let i = 0; i <this.selectedRowKeys.length; i++) {
          this.checkPagam={
            sjrq:[],
            bankNoCd:[]
          }
          this.checkPagam.sjrq[0]=this.dataSource[this.selectedRowKeys[i]].DATADATE;
          this.checkPagam.bankNoCd[0]=this.dataSource[this.selectedRowKeys[i]].BANKCODE;
          let url=`${window._CONFIG['domianURL']}`+"/messagemanagement/llbbMessageManagement/dayDownLoad?sjrq[]="+ this.checkPagam.sjrq+"&bankNoCd[]="+this.checkPagam.bankNoCd;
          /* window.open(url);*/
          try {
            var elemIF = document.createElement("iframe");
            elemIF.src = url;
            elemIF.style.display = "none";
            document.body.appendChild(elemIF);
          } catch (e) {}
        }

        that.onClearSelected();

        //let data=new Date();
        //downloadFile(url,data.getTime()+".zip",this.checkPagam);

        setTimeout(function(){
          that.loadData(1);
        },3000);
      },
      daySourceDown(){
        const that = this;
        if(this.selectedRowKeys.length==0){
          that.$message.warning("请选择你要批量下载的数据");
          return false;
        }
        var bool=false;
        for(var i=0;i<this.selectedRowKeys.length;i++) {
          if(this.dataSource[this.selectedRowKeys[i]].CREATESTATE==0){
            bool=true;
            break;
          }
        }
        if(bool){
          that.$message.warning("只能选择生成成功数大于0的数据");
          return;
        }
        for (let i = 0; i <this.selectedRowKeys.length; i++) {
          this.checkPagam={
            sjrq:[],
            bankNoCd:[]
          }
          this.checkPagam.sjrq[0]=this.dataSource[this.selectedRowKeys[i]].DATADATE;
          this.checkPagam.bankNoCd[0]=this.dataSource[this.selectedRowKeys[i]].BANKCODE;
          let url=`${window._CONFIG['domianURL']}`+"/messagemanagement/llbbMessageManagement/daySourceDown?sjrq[]="+
            this.checkPagam.sjrq+"&bankNoCd[]="+this.checkPagam.bankNoCd;
          try {
            var elemIF = document.createElement("iframe");
            elemIF.src = url;
            elemIF.style.display = "none";
            document.body.appendChild(elemIF);
          } catch (e) {}
        }

        that.onClearSelected();
        setTimeout(function(){
          that.loadData(1);
        },3000);
      },
      dayAfresh(){
        const that = this;
        if(this.selectedRowKeys.length==0){
          that.$message.warning("请选择你要重新报送的数据");
          return false;
        }
        this.checkPagam={
          sjrq:[],
          bankNoCd:[]
        }
        for(var i=0;i<this.selectedRowKeys.length;i++){
          this.checkPagam.sjrq[i]=this.dataSource[this.selectedRowKeys[i]].DATADATE;
          this.checkPagam.bankNoCd[i]=this.dataSource[this.selectedRowKeys[i]].BANKCODE;
        }
        let url="/messagemanagement/llbbMessageManagement/dayAfresh";
        this.loading = true;
        getAction(url,this.checkPagam).then((res)=>{
          that.onClearSelected();
          this.loading = false;
          if(res.success){
            that.$message.success(res.message);
            that.loadData(1);
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {

        })
      },
      dayRepulse(){
        const that = this;
        if(this.selectedRowKeys.length==0){
          that.$message.warning("请选择你要打回的数据");
          return false;
        }
        this.checkPagam={
          sjrq:[],
          bankNoCd:[]
        }
        for(var i=0;i<this.selectedRowKeys.length;i++){
          this.checkPagam.sjrq[i]=this.dataSource[this.selectedRowKeys[i]].DATADATE;
          this.checkPagam.bankNoCd[i]=this.dataSource[this.selectedRowKeys[i]].BANKCODE;
        }
        let url="/messagemanagement/llbbMessageManagement/dayRepulse";
        this.loading = true;
        getAction(url,this.checkPagam).then((res)=>{
          this.loading = false;
          that.onClearSelected();
          if(res.success){
            that.$message.success(res.message);
            that.loadData(1);
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {

        })
      },
      dayDelete(){
        const that = this;
        if(this.selectedRowKeys.length==0){
          that.$message.warning("请选择你要删除的数据");
          return false;
        }
        this.checkPagam={
          sjrq:[],
          bankNoCd:[]
        }
        for(var i=0;i<this.selectedRowKeys.length;i++){
          this.checkPagam.sjrq[i]=this.dataSource[this.selectedRowKeys[i]].DATADATE;
          this.checkPagam.bankNoCd[i]=this.dataSource[this.selectedRowKeys[i]].BANKCODE;
        }
        let url="/messagemanagement/llbbMessageManagement/dayDelete";
        this.loading = true;

        getAction(url,this.checkPagam).then((res)=>{
          that.onClearSelected();
          this.loading = false;
          if(res.success){
            that.$message.success(res.message);
            that.loadData(1);
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {

        })
      },
      BulkDownload(){
        //批量下载
        if(!this.url.bulkDownload){
          this.$message.error("请设置url.downloadG14Zip属性!")
          return;
        }
        var params = [];
        if(this.selectionRows.length > 0) {
          for (var a = 0; a < this.selectionRows.length; a++) {
            params.push(this.selectionRows[a].DATADATE + ":" +this.selectionRows[a].BANKNAME)

          }
        }else{
          this.$message.warning("请勾选需要下载的报表!")
          return;
        }
        that.onClearSelected();
        this.axios.post(`${window._CONFIG['domianURL']}/${this.url.bulkDownload}`,params,{'responseType': "blob"},).then(response=>{
          this.export_excel_file(response, "list_name.zip");
        })
      },
      export_excel_file(export_data,list_name){
        this.loading = true;
        let link = document.createElement("a");
        //    type就是blob的type,是MIME类型的，可以自己查看MIME类型都有哪些
        let blogw = new Blob([export_data],{type:"application/zip;charset=utf-8"})
        let objectUrl = window.URL.createObjectURL(blogw);    //创建一个新的url对象
        link.href = objectUrl;
        let file_name = list_name
        link.download = file_name;    //  下载的时候自定义的文件名
        link.click();
        window.URL.revokeObjectURL(objectUrl);   //为了更好地性能和内存使用状况，应该在适当的时候释放url.
        this.loadData()
        this.loading = fasle;

      },

      dayCheck(){
        const that = this;
        if(this.selectedRowKeys.length==0){
          that.$message.warning("请选择你要批量校验的数据");
          return false;
        }
        this.checkPagam={
          sjrq:[],
          bankNoCd:[]
        }
        for(var i=0;i<this.selectedRowKeys.length;i++){
          this.checkPagam.sjrq[i]=this.dataSource[this.selectedRowKeys[i]].DATADATE;
          this.checkPagam.bankNoCd[i]=this.dataSource[this.selectedRowKeys[i]].BANKCODE;
        }
        let url="/messagemanagement/llbbMessageManagement/dayCheck";
        this.loading = true;
        getAction(url,this.checkPagam).then((res)=>{
          that.onClearSelected();
          this.loading = false;
          if(res.success){
            that.$message.success(res.message);
            that.loadData(1);
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {

        })
      },
      bathSave(){
        const that = this;
        /*if(this.queryParam.sjrq=="" || this.queryParam.sjrq == undefined){
          that.$message.warning("请选择数据日期");
          return false;
        }*/


      },
      handleUpload() {
        const that = this;
        if(this.selectedRowKeys.length==0){
          that.$message.warning("请选择你要处理的数据");
          return false;
        }
        let ids="";
        for(var i=0;i<this.selectionRows.length;i++){
          let sjrq=this.selectionRows[i].DATADATE;
          let theme=this.selectionRows[i].THEME;
          let bankNoCd=this.selectionRows[i].BANK_NO_CD;
          ids = sjrq+"@"+theme+"@"+bankNoCd+","
        }
        var vurl =`${window._CONFIG['domianURL']}/messagemanagement/llbbMessageManagement/sendFtp?ids=`+ids;
        this.loading = true;
        getAction(vurl,this.checkPagam).then((res)=>{
          that.onClearSelected();
          that.loading = false;
          if(res.success){
            that.$message.success(res.message);
            that.loadData(1);
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {
        })
      },
      async createRebortData(){
        let that = this
        if(result.length == 0){
          that.$message.warning("请选择日期范围");
          return false;
        }
        if(result.length > 7){
          that.$message.warning("日期范围不能大于7天");
          return false;
        }
        this.loading = true;
        let url="/messagemanagement/llbbMessageManagement/dayReportNew";
        for(var i=0;i<result.length;i++) {
        var res = await this.axios.get(url,{params:{'sjrq':result[i]}});
          if(res.success){
            that.$message.success(result[i]+res.message);
            setTimeout(function(){
              that.loadData(1);
            },1500);
          }else {
            this.loading = false;
            if (res.result == null) {
              this.$message.error(res.message);
              break
            } else if (res.code == 501) {
              this.dataList = res.result;
              this.modal.title = '未提交业务表'
              this.modal.visible = true;
              break
            } else if (res.code == 502) {
              this.dataList = res.result;
              this.modal.title = '未表间校验业务表'
              this.modal.visible = true;
              break
            }else if(res.code == 503){
              this.dataList=res.result;
              this.modal.title='未锁库业务表'
              this.modal.visible=true;
              break
            }
          }
        }
        that.loadData(1);
        that.loading = false;
      },
      searchReset1() {
        result = []
        this.queryParam = {}
        this.loadData(1);
      },

      initDictConfig(){
      },
      reprotDetailList(record){
        this.$refs.dayReportItemList.edit(record);
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'bankNoCd',text:'法人标识'})
        fieldList.push({type:'date',value:'sjrq',text:'数据日期'})
        fieldList.push({type:'string',value:'khh',text:'客户号'})
        fieldList.push({type:'string',value:'nbjgh',text:'内部机构号'})
        fieldList.push({type:'string',value:'gmjjbmfl',text:'国民经济部门分类'})
        fieldList.push({type:'string',value:'jrjglxdm',text:'金融机构类型代码'})
        fieldList.push({type:'string',value:'qygm',text:'企业规模'})
        fieldList.push({type:'string',value:'kglx',text:'控股类型'})
        fieldList.push({type:'string',value:'jnjwbz',text:'境内境外标志'})
        fieldList.push({type:'string',value:'jyszdxzqhdm',text:'经营所在地行政区划代码'})
        fieldList.push({type:'string',value:'zcdz',text:'注册地址'})
        fieldList.push({type:'number',value:'sxed',text:'授信额度'})
        fieldList.push({type:'number',value:'yyed',text:'已用额度'})
        fieldList.push({type:'string',value:'sshy',text:'所属行业'})
        fieldList.push({type:'string',value:'nccsbz',text:'农村城市标志'})
        this.superFieldList = fieldList
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>